package myself.study.network.tcp.examples;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.Test;

/**
* @Name: TcpClient
* @Description: tcp协议数据传输客户端
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-1-12 下午1:16:35 
* @Version: V1.0
 */
public class TcpClient {
	
	@Test
	public void client() throws UnknownHostException, IOException {
		//声明客户端Socket对象
		Socket client = null ;
		//声明数据输入输出流对象
		DataInputStream dataInputStream = null ;
		DataOutputStream dataOutputStream = null ;
		try {
			//创建客户端Socket对象
			client = new Socket("127.0.0.1", 12345) ;
			//获取输出流对象
			dataOutputStream = new DataOutputStream(client.getOutputStream()) ;
			//发送客户端请求数据
			String requestData = "hello, tcp, 我来了！" ;
			dataOutputStream.writeUTF(requestData) ;
			System.out.println("to server : " + requestData);
			//获取输入流对象
			dataInputStream = new DataInputStream(client.getInputStream()) ;
			//获取服务端响应结果
			String responseData = dataInputStream.readUTF() ;
			System.out.println("from server : " + responseData);
		} catch (Exception e) {
			e.printStackTrace() ;
		} finally {
			//释放资源
			if(dataInputStream != null) {
				try {
					dataInputStream.close() ;
				} catch (Exception e2) {
					e2.printStackTrace() ;
				} finally {
					dataInputStream = null ;
				}
			}
			if(dataOutputStream != null) {
				try {
					dataOutputStream.close() ;
				} catch (Exception e2) {
					e2.printStackTrace() ;
				} finally {
					dataOutputStream = null ;
				}
			}
			if(client != null) {
				try {
					client.close() ;
				} catch (Exception e2) {
					e2.printStackTrace() ;
				} finally {
					client = null ;
				}
			}
		}
	}

}
